package com.wtwd.campus.encryptnetty;

import com.wtwd.campus.netty.ChannelHandler;
import com.wtwd.campus.netty.ChannelMap;
import com.wtwd.campus.receiver.Receiver;
import com.wtwd.campus.receiver.ReceiverFactory;
import com.wtwd.campus.utils.AESUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 处理连接与通讯
 */
public class EncryptServerHandler extends ChannelInboundHandlerAdapter {
    private final static Logger logger = LoggerFactory.getLogger(EncryptServerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
     /*   InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        System.out.println("收到客户端[ip:" + clientIp + "]连接");*/
        Channel channel = ctx.channel();
        logger.info("[channel id:{} device addr:{}] msg:{}", channel.id(), channel.remoteAddress());
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 1.解密,并且截取掉最后一位
        String decryptMsg = null;
        try {
            logger.info("[channel id:{}] 收到未解密消息:{}", ctx.channel().id(), msg.toString());
            decryptMsg = AESUtils.decrypt(msg.toString());
            decryptMsg = decryptMsg.substring(0, decryptMsg.length() - 1);
        } catch (Exception e) {
            logger.error("[channel id:{}] 指令解密失败：",ctx.channel().id());
            return;
        }
        try {
            // 1.msg转为实际操作实体类
            Receiver receiver = ReceiverFactory.createReceiver(decryptMsg);
            logger.info("[channel id:{}] 解析指令成功:{}", ctx.channel().id(), decryptMsg);
            if (receiver != null) {
                String[] split = decryptMsg.split(",");
                String imei = split[1];
                //3. 保存或者刷新通道
                EncryptChannelHandler.addOrRefreshChannel(imei, ctx.channel());
                //4. 处理数据
                receiver.parseMessage(decryptMsg);
            }
        } catch (Exception e) {
            logger.error("[channel id:{}] 指令解析或处理失败",ctx.channel().id());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        logger.info("[channel id:{}] imei={},发生异常，关闭通道", ctx.channel().id(), EncryptChannelMap.getKey(ctx.channel()));
        ChannelHandler.closeChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("[channel id:{}] imei={},设备主动断开连接，关闭通道", ctx.channel().id(), EncryptChannelMap.getKey(ctx.channel()));
        ChannelHandler.closeChannel(ctx.channel());
    }

}